package com.umessage.hotel.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.umessage.common.annotation.Log;
import com.umessage.common.controller.BaseController;
import com.umessage.common.domain.QueryRequest;
import com.umessage.common.domain.ResponseBo;
import com.umessage.hotel.domain.HotelInfo;
import com.umessage.hotel.domain.PictureInfo;
import com.umessage.hotel.domain.RoomInfo;
import com.umessage.hotel.domain.RoomStatus;
import com.umessage.hotel.service.HotelInfoService;
import com.umessage.hotel.service.PictureInfoService;
import com.umessage.hotel.service.RoomInfoService;
import com.umessage.hotel.service.RoomStatusService;
import com.umessage.hotel.service.WxCfgService;
import com.umessage.system.domain.Dict;
import com.umessage.system.domain.User;
import com.umessage.system.service.DictService;

@Controller
@RequestMapping("hotel")
public class HotelInfoController extends BaseController{
	
	@Autowired
	private HotelInfoService hotelService;
	@Autowired
	private RoomInfoService roomService;
	@Autowired
	private DictService dictService;
	@Autowired
	private PictureInfoService picService;
	@Autowired
	private RoomStatusService roomStatusService;
	@Autowired
	FastFileStorageClient fastFileStorageClient;
	/**
	 * 酒店首页
	 * @return
	 */
	@RequestMapping("index")
	public String index() {
		return "hotel/hotel/hotel";
	}
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> listHotels(QueryRequest request,HotelInfo hotel) {
		//HotelInfo hotel=new HotelInfo();
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<HotelInfo> list = hotelService.findAllHotels(hotel);
		PageInfo<HotelInfo> pageInfo = new PageInfo<HotelInfo>(list);
		return getDataTable(pageInfo);
	}
	@RequestMapping("add")
	@ResponseBody
	public ResponseBo addHotelInfo(HotelInfo hotel) {
		try {
			User user = super.getCurrentUser();
			Integer type = hotelService.addHotelInfo(hotel,user);
			return ResponseBo.ok(type);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseBo.error("添加酒店信息失败，请联系网站管理员！");
		}
	}
	@RequestMapping("toUpdate")
	public String toUpdateHotelInfo() {
		return "hotel/hotel/hotelEdit";
	}
	
	@RequestMapping("getHotel")
	@ResponseBody
	public Map<String, Object> hotelInfoById(String hotelId) {
		Map<String, Object> hotelMap = new LinkedHashMap<>();
		User user = super.getCurrentUser();
		if(hotelId==null) {
			if(user.getHotelId()!=null) {
				hotelId=user.getHotelId();
			}else {
				return null;
			}
		}
		HotelInfo hotel= this.hotelService.findHotelsById(hotelId);
		if(user.getHotelId()!=null) {
			PictureInfo pic=new PictureInfo();
			pic.setTableName("t_hotel_info");
			pic.setTableId(hotel.getHotelId());
			List<PictureInfo> pics = this.picService.findPicturesPC(pic);
			Object[] objs= pics.toArray();
			hotel.setPictures(objs);
			Dict dict=new Dict();
			dict.setTableName("t_hotel_info");
			dict.setFieldName("facilities");
			List<Dict> dictFacList=this.dictService.findAllDicts(dict);
			dict.setFieldName("policies");
			List<Dict> dictPolList=this.dictService.findAllDicts(dict);
			hotelMap.put("facList",dictFacList);
			hotelMap.put("polList",dictPolList);
		}
		hotelMap.put("hotel",hotel);
		return hotelMap;
		
	}
	
	@RequestMapping("update")
	@ResponseBody
	public ResponseBo updateHotelInfo(HotelInfo hotel) {
		try {
			User user = super.getCurrentUser();
			hotel.setModifyTime(new Date());
			hotel.setModifyAcc(user.getUserId()+"");
			String invoiceType = hotel.getInvoiceType() ==null ? "0":hotel.getInvoiceType();
			hotel.setInvoiceType(invoiceType);
			Integer type = hotelService.updateHotel(hotel);
			if(type==0) {
				return ResponseBo.ok(type);
			}else {
				if(user.getHotelId()==null) {
					return ResponseBo.ok(1);
				}
				PictureInfo pic=new PictureInfo();
				pic.setAddTime(new Date());
				pic.setAddAcc(user.getUserId()+"");
				pic.setTableId(hotel.getHotelId()+"");
				pic.setType("0");
				pic.setTableName("t_hotel_info");
				Object[] objs=hotel.getPictures();
				this.picService.savePics(objs,pic);
				return ResponseBo.ok(type);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseBo.error("编辑酒店信息失败，请联系网站管理员！");
		}
	}
	/**
	 * 删除酒店信息  is_delete
	 * @param hotelId
	 */
	@RequestMapping("delete")
	@ResponseBody
	public ResponseBo deleteHotel(String ids) {
		try {
			this.hotelService.updateHotels(ids);
			return ResponseBo.ok("成功删除！");
		} catch (Exception e) {
			return ResponseBo.error("删除信息失败，请联系网站管理员！");
		}
	}
	/**
	 * 跳转房间/房态/编辑房间页面
	 * @param roomId
	 * @param rtype
	 * @param model
	 * @return
	 */
	@RequestMapping(value="roomIndex",method=RequestMethod.POST)
	public String roomIndex(String roomId,String rtype,Model model) {
		User user = super.getCurrentUser();
		HotelInfo hotel= this.hotelService.findHotelsById(user.getHotelId()+"");
		model.addAttribute("hotel", hotel);
		// rtype 1增加 2编辑 3房态
		if(roomId!=null) {
			model.addAttribute("roomId", roomId);
			//跳转到房间编辑页面
			if("2".equals(rtype)) {
				RoomInfo roomInfo=this.getRoomInfoById(roomId);
				model.addAttribute("roomInfo", roomInfo);
				Dict dict=new Dict();
				dict.setTableName("t_room_info");
				dict.setFieldName("facilities");
				List<Dict> facDicts = this.dictService.findAllDicts(dict);
				dict.setFieldName("policies");
				List<Dict> polDicts = this.dictService.findAllDicts(dict);
				model.addAttribute("facDicts", facDicts);
				model.addAttribute("polDicts", polDicts);
				return "hotel/hotel/roomAdd";			
			}
			//跳转到房态管理页面
			if("3".equals(rtype)) {
				return "hotel/hotel/roomBook";
			}
		}else {
			//跳转到房间添加页面
			if("1".equals(rtype)) {
				Dict dict=new Dict();
				dict.setTableName("t_room_info");
				dict.setFieldName("facilities");
				List<Dict> facDicts = this.dictService.findAllDicts(dict);
				dict.setFieldName("policies");
				List<Dict> polDicts = this.dictService.findAllDicts(dict);
				model.addAttribute("facDicts", facDicts);
				model.addAttribute("polDicts", polDicts);
				model.addAttribute("roomInfo", new RoomInfo());
				return "hotel/hotel/roomAdd";
			}
		}
		return "hotel/hotel/room";
	}
	@Log("获取单个房间基本信息")
	public RoomInfo getRoomInfoById(String roomId) {
		RoomInfo roomInfo=new RoomInfo();
		User user = super.getCurrentUser();
		roomInfo.setRoomId(Integer.valueOf(roomId));
		roomInfo.setHotelId(user.getHotelId()+"");
		roomInfo=this.roomService.getRoomInfoById(roomInfo);
		return roomInfo;
	}
	@Log("房间信息列表")
	@RequestMapping("roomList")
	@ResponseBody
	public Map<String, Object> getRoomInfo(QueryRequest request,RoomInfo roomInfo) {
		User user = super.getCurrentUser();
		if(user.getHotelId()!=null) {
		roomInfo.setHotelId(user.getHotelId());
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<RoomInfo> list = this.roomService.findRoomInfoByCon(roomInfo);
		//List<RoomInfo> list = this.roomService.findRoomInfoAll(null,user.getHotelId(),"1");
		PageInfo<RoomInfo> pageInfo = new PageInfo<RoomInfo>(list);
		return getDataTable(pageInfo);
		}
		return null;
	}
	@Log("添加酒店房间")
	@RequestMapping(value="addRoom",method=RequestMethod.POST)
	@ResponseBody
	public ResponseBo addRoom(RoomInfo roomInfo) {
		try {
			User user = super.getCurrentUser();
			roomInfo.setAddTime(new Date());
			roomInfo.setAddAcc(user.getUserId());
			roomInfo.setModifyTime(new Date());
			roomInfo.setModifyAcc(user.getUserId());
			roomInfo.setHotelId(user.getHotelId()+"");
			roomInfo.setIsBookable("1");
			this.roomService.addRoomInfoAndPic(roomInfo);
			return ResponseBo.ok("添加房间信息成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseBo.error("添加房间信息失败，请联系网站管理员！");
		}
	}
	@Log("根据id编辑酒店房间信息")
	@RequestMapping(value="editRoom",method=RequestMethod.POST)
	@ResponseBody
	public ResponseBo editRoomById(RoomInfo roomInfo) {
		try {
			User user = super.getCurrentUser();
			roomInfo.setModifyTime(new Date());
			roomInfo.setModifyAcc(user.getUserId());
			roomInfo.setHotelId(user.getHotelId()+"");
			this.roomService.editRoomById(roomInfo);
			return ResponseBo.ok("编辑房间信息成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseBo.error("编辑房间信息失败，请联系网站管理员！");
		}
	}
	@Log("删除图片")
	@RequestMapping("delPicture")
	@ResponseBody
	public String delPicture(Integer picId) {
		try {
			this.picService.delPicture(picId);
			PictureInfo pic = this.picService.selectByKey(picId);
			if(pic!=null) {
				String path=pic.getPicUrl();
				// 第一种删除：参数：完整地址
				fastFileStorageClient.deleteFile(path);
			}
			return "删除成功";
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "删除失败";
		}
		
	}
	@Log("查询酒店房间类型")
	@RequestMapping("getRoomName")
	@ResponseBody
	public ResponseBo getRoomType() {
		try {
			User user = super.getCurrentUser();
			RoomInfo roomInfo=new RoomInfo();
			roomInfo.setHotelId(user.getHotelId()+"");
			List<RoomInfo> list = this.roomService.findRoomInfoByCon(roomInfo);
			return ResponseBo.ok(list);
		}catch (Exception e) {
			e.printStackTrace();
			return ResponseBo.error("获取信息失败");
		}
	}
	@Log("查询酒店房间某月的预定信息")
	@RequestMapping("getMonthRoom")
	@ResponseBody
	public Map<String, Object> getDailyRoom(String roomId,Integer year,Integer month) {
			User user = super.getCurrentUser();
			Calendar cale = Calendar.getInstance();
			if(year==null) {
				year=cale.get(Calendar.YEAR);
			}
			Integer	defaultMonth=cale.get(Calendar.MONTH)+1;
			if(month==null) {
				month=defaultMonth;
			}
			cale.set(Calendar.YEAR, year);
			cale.set(Calendar.MONTH, month - 1); 
			cale.set(Calendar.DATE, 1);
			cale.roll(Calendar.DATE, -1);
			int day = cale.get(Calendar.DATE);
//			cale.add(month, 1);
//			cale.set(Calendar.DAY_OF_MONTH, 0);
//			int day=cale.get(Calendar.DAY_OF_MONTH);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			String beginStr=year+"-"+month+"-"+1;
			String endStr=year+"-"+month+"-"+day;
			try {
				Date endTime = sdf.parse(endStr);
				Date beginTime = sdf.parse(beginStr);
				Map<String,Object> map=new HashMap<>();
				map.put("roomId", roomId);
				map.put("hotelId", user.getHotelId());
				map.put("endTime", endTime);
				map.put("beginTime", beginTime);
				List<RoomInfo> rooms = this.roomService.findRoomInfoAll(roomId,user.getHotelId(),"1");
				//获取当前月中有修改的房态
				List<RoomStatus> rss = this.roomStatusService.findRoomStatusAdmin(map);
				List<RoomStatus> rsList=new ArrayList<>();
				if(rooms!=null&&rooms.size()>0) {
					RoomInfo roomInfo=rooms.get(0);
					for (int i = 1; i <= day; i++) {
						RoomStatus rs=new RoomStatus();
						if(rss!=null&&rss.size()>0) {
							for (int j=0; j<rss.size();j++) {
								cale.setTime(rss.get(j).getRoomDate());
								int daily=cale.get(Calendar.DAY_OF_MONTH);
								if(i==daily) {
									rs.setPrice(rss.get(j).getPrice());
									rs.setIsBook(rss.get(j).getIsBook());
//									rs.setHotelId(roomInfo.getHotelId());
//									rs.setRoomId(roomId);
//									rs.setDaily(i+"");
									break;
								}else {
									rs.setPrice(roomInfo.getOriginalPrice());
									rs.setIsBook(roomInfo.getIsBookable());
								}
							}
						}else {
							rs.setPrice(roomInfo.getOriginalPrice());
							rs.setIsBook(roomInfo.getIsBookable());
						}
						rs.setHotelId(roomInfo.getHotelId());
						rs.setRoomId(roomId);
						rs.setDaily(i+"");
						rsList.add(rs);
					}
				}
				PageInfo<RoomStatus> pageInfo = new PageInfo<RoomStatus>(rsList);
				return getDataTable(pageInfo);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			
			
	}
	@ResponseBody
	@RequestMapping("book")
	public ResponseBo bookRoomStatus(BigDecimal price,String isBook,String daily,String month,String year,Integer roomId) {
		try {
			RoomInfo roomInfo=new RoomInfo();
			User user = super.getCurrentUser();
			roomInfo.setRoomId(roomId);
			roomInfo.setHotelId(user.getHotelId()+"");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			String endStr=year+"-"+month+"-"+daily;
			Date endTime = sdf.parse(endStr);
			Date beginTime = null;
			RoomStatus rs=new RoomStatus();
			rs.setRoomId(String.valueOf(roomId));
			rs.setHotelId(user.getHotelId()+"");
			rs.setRoomDate(endTime);
			rs.setIsBook(isBook);
			rs.setPrice(price);
			Map<String,Object> map=new HashMap<>();
			map.put("roomId", roomId);
			map.put("hotelId", user.getHotelId());
			map.put("endTime", endTime);
			map.put("beginTime", beginTime);
			List<RoomStatus> rss = this.roomStatusService.findRoomStatus(map);
			if(rss!=null&&rss.size()>0) {
				rs.setId(rss.get(0).getId());
				this.roomStatusService.updateNotNull(rs);
			}else {
				this.roomStatusService.save(rs);
			}
			return ResponseBo.ok("编辑信息成功");
		}catch (Exception e) {
			e.printStackTrace();
			return ResponseBo.error("编辑信息失败，请联系网站管理员！");
		}
	}
/*	@Log("获取酒店Title(酒店名称 /酒店ID)")
	@RequestMapping("title")
	@ResponseBody
	public HotelInfo hotelTitelById() {
		User user = super.getCurrentUser();
		if(user.getHotelId()!=null) {
			HotelInfo hotel= this.hotelService.findHotelsById(user.getHotelId()+"");
			return hotel;
		}
		return null;
	}*/
	
}
